<template>
  <div :style="{ width: width, height: height }">
    <!-- 图片 -->
    <template v-if="metaData.fileCategory == 0">
      <image-preview :src="downloadFileStream(metaData.id)" width="100%" height="100%" />
    </template>
    <!-- 视频 -->
    <template v-else-if="metaData.fileCategory == 1">
      <video controls class="videoComponent" ref="videoComponent"></video>
    </template>
    <!-- 音频 -->
    <template v-else-if="metaData.fileCategory == 2">
      <audio ref="audioComponent" class="audioComponent" controls />
    </template>
    <!-- 文档 -->
    <template v-else-if="metaData.fileCategory == 4">
      <iframe
        :src="`https://view.officeapps.live.com/op/view.aspx?src=${downloadFileStream(metaData.id)}`"
        :style="{ width: width, height: height }" />
    </template>
    <!-- 下载 -->
    <a :href="downloadFileStream(metaData.id)" :download="`${metaData.id}.${metaData.fileSuffix}`">点击下载</a>
  </div>
</template>

<script>
import ImagePreview from '@/components/ImagePreview'
import { downloadFileStream, downloadFile } from '@/utils/file'
export default {
  name: 'MetaPreview',
  components: {
    ImagePreview,
  },
  props: {
    width: {
      type: [Number, String],
      default: '100%',
    },
    height: {
      type: [Number, String],
      default: '100%',
    },
    //当前文件对象
    metaData: {
      type: Object,
      default: {
        id: 0,
        //文件分类
        fileCategory: 0,
        //文件后缀
        fileSuffix: '',
      },
    },
  },
  data() {
    return {
      videoComponent: {},
      audioComponent: {},
    }
  },
  methods: {
    // 下载文件
    downloadFileStream,
    // 下载文件
    downloadFile,
    //初始化
    init() {
      this.videoComponent = this.$refs.videoComponent
      this.audioComponent = this.$refs.audioComponent
      var component = {}
      switch (this.metaData.fileCategory) {
        case 1:
          component = this.videoComponent
          break
        case 2:
          component = this.audioComponent
          break
      }
      component.src = downloadFileStream(this.metaData.id)
    },
    //停止播放
    pause() {
      var video = this.videoComponent
      if (video) {
        video.pause()
      }
      var audio = this.audioComponent
      if (audio) {
        audio.pause()
      }
    },
  },
  destroyed() {
    var video = this.videoComponent
    if (video) {
      video.dispose()
    }
    var audio = this.audioComponent
    if (audio) {
      audio.dispose()
    }
  },
}
</script>

<style lang="scss" scoped>
.videoComponent {
  width: 100%;
}
.audioComponent {
  width: 100%;
}
</style>
